package com.nf.health.app.sport_recipe.activity;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.customview.BrokenLineBackground;
import com.nf.health.app.customview.NewBrokenLine;
import com.nf.health.app.http.Act;
import com.nf.health.app.sport_recipe.bean.EnduranceTestBean;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.Util;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;



/**
 * Created by changpeng on 2017/04/19.
 * 跑步机心肺耐力测试报告
 */
public class EnduranceTestActivity extends BaseActivity {

    @Bind(R.id.rl_broken_line_bg)
    RelativeLayout rl_broken_line_bg;
    @Bind(R.id.rl_broken_line)
    LinearLayout rl_broken_line;

    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    @Bind(R.id.tv_sex)
    TextView mTvSex;
    @Bind(R.id.tv_age_)
    TextView mTvAge;
    @Bind(R.id.tv_height)
    TextView mTvHeight;
    @Bind(R.id.tv_weight)
    TextView mTvWeight;
    @Bind(R.id.tv_quiet_rate)
    TextView mTvQuietRate;
    @Bind(R.id.tv_test_time)
    TextView mTvTestTime;
    @Bind(R.id.tv_num)
    TextView mTvNum;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_intension_1)
    TextView mTvIntension1;
    @Bind(R.id.tv_intension_2)
    TextView mTvIntension2;
    @Bind(R.id.tv_intension_3)
    TextView mTvIntension3;
    @Bind(R.id.tv_heart_rate1)
    TextView mTvHeartRate1;
    @Bind(R.id.tv_heart_rate2)
    TextView mTvHeartRate2;
    @Bind(R.id.tv_heart_rate3)
    TextView mTvHeartRate3;
    @Bind(R.id.tv_suggest)
    TextView mTvSuggest;
    @Bind(R.id.tv_p3)
    TextView mTvP3;
    private String hpuid = "";
    private LineChart mLineChar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.layout_common_header);
        setContent(R.layout.activity_endurance_test);
        ButterKnife.bind(this);
        initView();
        initData();

    }

    private void initView() {
        mLineChar = (LineChart) findViewById(R.id.chart1);
        titlebarTitleTv.setText("跑步机心肺耐力测试报告");
        hpuid = getIntent().getStringExtra("hpuid");
    }

    private void initData() {
        provider.getYDRunningInfo(hpuid);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (Act.Flag.FLAG_YD_RUNNINGINFO.equals(actionName)) {
            Gson gson = new MyGsonBuilder().createGson();
            EnduranceTestBean bean = gson.fromJson(object + "", EnduranceTestBean.class);
            setDataToView(bean);
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
    }

    private void setDataToView(EnduranceTestBean bean){
        if(bean == null){
            return;
        }
        mTvIntension1.setText(bean.getIntension1());
        mTvIntension2.setText(bean.getIntension2());
        mTvIntension3.setText(bean.getIntension3());
        mTvHeartRate1.setText(bean.getHeartrate1());
        mTvHeartRate2.setText(bean.getHeartrate2());
        mTvHeartRate3.setText(bean.getHeartrate3());
        mTvSuggest.setText(bean.getAdvice()+"");
        mTvNum.setText(""+bean.getNum());
        mTvName.setText(bean.getName());
        mTvSex.setText(Util.getSex(bean.getSex()));
        mTvAge.setText(bean.getAge()+"");
        mTvHeight.setText(bean.getHeight());
        mTvWeight.setText(bean.getWeight());
        mTvQuietRate.setText(bean.getRestheartrate());
        mTvP3.setText("心脏功能能力(F.C) : "+bean.getP3()+" METs");
        String time = DateUtil.date2String(bean.getCreatetime(),"yyyy-MM-dd");
        mTvTestTime.setText(time);

        List<Float> yValue = new ArrayList<Float>();
        yValue.add(Float.parseFloat(bean.getHeartrate1()));
        yValue.add(Float.parseFloat(bean.getHeartrate2()));
        yValue.add(Float.parseFloat(bean.getHeartrate3()));
        List<String> xText = new ArrayList<String>();
        xText.add(bean.getIntension1());
        xText.add(bean.getIntension2());
        xText.add(bean.getIntension3());
        refreshLine(yValue,xText);

        float y = Float.parseFloat(bean.getP2());
        float x = bean.getAge();
        initHeartLine(x,y);
    }

    private void refreshLine(List<Float> yValue,List<String> xText){
        List<String> y_array  = new ArrayList<String>();
        y_array.add("0");
        y_array.add("20");
        y_array.add("40");
        y_array.add("60");
        y_array.add("80");
        y_array.add("100");
        y_array.add("120");
        y_array.add("140");
        y_array.add("160");


        String max = "160";
        String min = "0";
        rl_broken_line_bg.removeAllViews();
        rl_broken_line_bg.addView(new BrokenLineBackground(this, y_array,0));
        rl_broken_line.removeAllViews();
        rl_broken_line.addView(new NewBrokenLine(this, yValue,xText, Float.parseFloat(max),Float.parseFloat(min), y_array.size()));
    }

    /**
     * 心率图
     * @param xs  红点(标记)的横坐标
     * @param ys
     */
    private void initHeartLine(float xs,float ys){
        Description desc = new Description();
        desc.setText("");
        mLineChar.setDescription(desc);
        //设置支持触控手势
        mLineChar.setTouchEnabled(false);
        //设置缩放
        mLineChar.setDragEnabled(false);
        XAxis xAxis = mLineChar.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //xAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置x轴的最大值
        xAxis.setAxisMaximum(60f);
        //设置x轴的最小值
        xAxis.setAxisMinimum(10f);
        xAxis.setDrawGridLines(false);


        YAxis leftAxis = mLineChar.getAxisLeft();
        //重置所有限制线,以避免重叠线
        leftAxis.removeAllLimitLines();
        //y轴最大
        leftAxis.setAxisMaximum(16f);
        //y轴最小
        leftAxis.setAxisMinimum(6f);
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(false);
        leftAxis.setDrawGridLines(false);
        // 限制数据(而不是背后的线条勾勒出了上面)
        leftAxis.setDrawLimitLinesBehindData(true);

        mLineChar.getAxisRight().setEnabled(false);

        Legend l = mLineChar.getLegend();
        l.setForm(Legend.LegendForm.NONE);


        //创建三条曲线的坐标集合
        ArrayList<Entry> e1 = new ArrayList<Entry>();
        for (int i = 10; i <= 60; i++) {
            float y = (float) (-0.000002708*i*i*i*i+0.0004856*i*i*i-0.03216*i*i+0.8343*i+3.517);
            e1.add(new Entry(i, y));
            Log.e("line", "x=" + i + ",,y=" + y);
        }

        ArrayList<Entry> e2 = new ArrayList<Entry>();
        for (int i = 10; i <= 60; i++) {
            float y = (float) (-0.000005833*i*i*i*i+0.000963*i*i*i-0.05778*i*i+1.394*i+1.933);
            e2.add(new Entry(i, y));
        }

        ArrayList<Entry> e3 = new ArrayList<Entry>();
        for (int i = 10; i <= 60; i++) {
            float y = (float) (-0.000006458*i*i*i*i+0.001048*i*i*i-0.06142*i*i+1.457*i+4.083);
            e3.add(new Entry(i, y));
        }



        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        //添加数据集
        ArrayList<Entry> dot = new ArrayList<Entry>();
        dot.add(new Entry(xs,ys));
        LineDataSet set1 = new LineDataSet(dot,"");
        set1.setDrawCircles(true);
        set1.setCircleRadius(4.5f);
        set1.setCircleColor(Color.RED);
        set1.setCircleSize(5);
        set1.setDrawCircleHole(false);
        dataSets.add(set1);

        //创建位于顶部的一条直线，并填充背景色,也就是设置整个图表的背景
        ArrayList<Entry> top = new ArrayList<Entry>();
        top.add(new Entry(10,16));
        top.add(new Entry(60,16));

        LineDataSet set2 = new LineDataSet(top,"");
        set2.setColor(getResources().getColor(R.color.theme_color));
        set2.setDrawValues(false);
        set2.setDrawCircles(false);
        set2.setDrawFilled(true);
        set2.setFillAlpha(255);
        set2.setFillColor(getResources().getColor(R.color.theme_color));

        //add 的顺序需要注意，先add 范围最大，也就是背景图的线，然后一个个覆盖
        dataSets.add(set2);
        dataSets.add(setDataF(e3, getResources().getColor(R.color.line_3)));
        dataSets.add(setDataF(e2, Color.WHITE));
        dataSets.add(setDataF(e1, getResources().getColor(R.color.line_1)));

        //创建一个数据集的数据对象
        LineData data = new LineData(dataSets);

        //谁知数据
        mLineChar.setData(data);
        mLineChar.invalidate();
    }

    //传递数据集
    private LineDataSet setDataF(ArrayList<Entry> values, int color) {
        // 创建一个数据集,并给它一个类型
        LineDataSet set1 = new LineDataSet(values,"");

        // 在这里设置线
        set1.setDrawValues(false);
        set1.setDrawCircles(false);
        set1.setColor(color);
        set1.setFillColor(color);
        set1.setCircleColor(Color.BLACK);
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setDrawFilled(true);
        set1.setFillAlpha(255);
        set1.setFormLineWidth(1f);
        set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
        set1.setFormSize(15.f);

        return set1;
    }
}
